import React from 'react';
import {connect} from 'dva';
import styles from './Candidates.css';
import {Table, Card, Col, Row, Spin, Button, message} from 'antd';
import MainLayout from '../components/layouts/MainLayout';
import {routerRedux}  from 'dva/router';

function Candidates({candidates, dispatch, location}) {
  function handleDelete(id) {
    dispatch({
      type: 'candidates/remove',
      payload: {
        id: id
      }
    });
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'operation',
      render(text, record, index) {
        return (
          <div>
            <Button ghost={true} onClick={() => handleDelete(record.id)} type="danger" icon="delete"/>
          </div>
        );
      }
    }
  ];

  function handleAddCandidate() {
    dispatch(routerRedux.push({
      pathname: 'candidateadd',
      query: {}
    }));
  }

  function handlePageChange(page, pageSize) {
    dispatch({
      type: 'candidates/startLoading',
      payload: {}
    });

    dispatch({
      type: 'candidates/fetch',
      payload: {
        page: page,
        page_size: pageSize
      }
    });
  }

  const pagination = {
    total: candidates.total,
    onChange: (page, pageSize)=> {
      handlePageChange(page, pageSize);
    }
  };

  if (candidates.loading) {
    return (
      <MainLayout location={location}>
        <Row>
          <Col span={3}>

          </Col>
          <Col span={18}>
            <Card title="候选对象列表" extra={<a onClick={() => handleAddCandidate()}>新增</a>}>
              <Spin>
                <Table
                  dataSource={candidates.list}
                  columns={columns}
                  pagination={pagination}
                />
              </Spin>
            </Card>
          </Col>
          <Col span={3}>

          </Col>
        </Row>
      </MainLayout>
    );
  }


  return (
    <MainLayout location={location}>
      <Row>
        <Col span={3}>

        </Col>
        <Col span={18}>
          <Card title="候选对象列表" extra={<a onClick={() => handleAddCandidate()}>新增</a>}>
            <Table dataSource={candidates.list} columns={columns}/>
          </Card>
        </Col>
        <Col span={3}>

        </Col>
      </Row>
    </MainLayout>
  );
}

function mapStateToProps({candidates}) {
  return {
    candidates: candidates
  };
}

export default connect(mapStateToProps)(Candidates);
